#include "StdAfx.h"
#include "TextureManager.h"
#include "Texture.h"

#include <assert.h>

using namespace Fossil;
void TextureManager::Initialise()
{
	ilInit();
	iluInit();
}

void TextureManager::Destroy()
{
	//Delete all textures
	for(TextureMapIterator iter = m_Textures.begin(); iter != m_Textures.end(); ++iter)
	{
		delete iter->second;
	}
	m_Textures.clear();

	Singleton::Destroy();
}

Texture* TextureManager::GetTexture(const char* Filename)
{
	Texture* pTexture = 0;
	TextureMapIterator iter = m_Textures.find(Filename);
	if(iter == m_Textures.end())
	{
		pTexture = LoadTexture(Filename);
		m_Textures.insert(std::pair<const char*, Texture*>(Filename, pTexture));
	}
	else
	{
		pTexture = iter->second;
	}
	return pTexture;
}

Texture* TextureManager::LoadTexture(const char* Filename)
{
	ILuint tempHandle;
	ilGenImages(1, &tempHandle);
	ilBindImage(tempHandle);
	
	if(!ilLoadImage(Filename))
	{
		assert(IL_NO_ERROR == ilGetError());
		return NULL;
	}

	Texture* pTexure = new Texture();

	pTexure->m_Format	= ilGetInteger(IL_IMAGE_FORMAT);
	pTexure->m_Width	= ilGetInteger(IL_IMAGE_WIDTH);
	pTexure->m_Height	= ilGetInteger(IL_IMAGE_HEIGHT);
	pTexure->m_Bpp		= ilGetInteger(IL_IMAGE_BPP);

	glGenTextures(1, &pTexure->m_Handle);
	glBindTexture(GL_TEXTURE_2D, pTexure->m_Handle);

	assert(GL_NO_ERROR == glGetError());

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	glTexImage2D(	GL_TEXTURE_2D, 
					0,
					pTexure->m_Bpp,
					pTexure->m_Width,
					pTexure->m_Height,
					0,
					pTexure->m_Format,
					GL_UNSIGNED_BYTE,
					ilGetData()
				);	

	ilDeleteImage(tempHandle);

	assert(GL_NO_ERROR == glGetError());

	return pTexure;
}
